package com.flink.window;

import com.flink.func.WaterSensorMapFunction;
import com.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * WindowAggregateDemo
 *
 * @author caizhiyang
 * @since 2024-02-26
 */
public class WindowAggregateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.socketTextStream("localhost", 7777)
                //转换成WaterSensor
                .map(new WaterSensorMapFunction())
                //按键分组
                .keyBy(w -> w.getId())
                //设置滚动窗口,窗口大小为10秒
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                //设置聚合操作
                .aggregate(new AggregateFunction<WaterSensor, Integer, String>() {
                    @Override
                    public Integer createAccumulator() {
                        System.out.println("创建累加器");
                        return 0;
                    }

                    @Override
                    public Integer add(WaterSensor waterSensor, Integer accumulator) {
                        System.out.println("调用add方法,value=" + waterSensor);
                        return accumulator + waterSensor.getVc();
                    }

                    @Override
                    public String getResult(Integer accumulator) {
                        System.out.println("调用getResult方法");
                        return accumulator.toString();
                    }

                    @Override
                    public Integer merge(Integer integer, Integer acc1) {
                        System.out.println("调用merge方法");
                        return null;
                    }
                }).print();

        env.execute();
    }
}
